<?php

require_once('../../includes/classes/core.php');
mysql_query("SET NAMES 'utf8'");
$action 	= $_REQUEST['act'];
$error		= '';
$data		= '';

switch ($action) {
	case 'checker':
	    $data = array(
	       'chat' => array()
	    );
	    mysql_query("SET @i = 0;");
        $checker = mysql_query("SELECT 	chat.`id`,
                        				chat.`ip`,
                        				chat.`name`,
                                        'წერს' AS `order`,
                                        SEC_TO_TIME((NOW() - chat.`start_date`)) AS `date`,
                                        users.`ext`,
                                        chat.`user_id`,
                                        @i := @i + 1 AS `num`,
                                        IF(@i = 1, '', IF(@i = 2, '#E64A45', IF(@i = 3, '#257E78', IF(@i = 4, '#29264E', IF(@i = 5, '#00904B',''))))) AS `color`
                                FROM 	`chat`
                                JOIN users ON chat.user_id = users.id
                                WHERE 	chat.`status`   = 0
                                AND 	chat.`actived`  = 1;");
        
        mysql_query("SET @r = 0;");
        $checker1 = mysql_query("   SELECT 	`id`,
                            				`ip`,
                            				`name`,
                                            @r := @r + 1 AS `order`,
                                            SEC_TO_TIME((NOW() - `start_date`)) AS `date`,
                                            `user_id`
                                    FROM 	`chat`
                                    WHERE 	`status`   = 0
                                    AND 	`actived`  = 1;");
        
        $station = '<h2>სთეიშენები</h2>
                      <table id="all_chat">
                      <tr>
                        <th style="display:none;"></th>
                        <th>სთეიშენი</th>
                        <th>სტატუსი</th>
                        <th>დრო</th>
                        <th>აბონენტი</th>
                        <th>IP</th>
                      </tr>
                      <tr>
                    ';
        
        $queu = '
            <h2>რიგი</h2>
                      <table id="all_chat">
                      <tr>
                        <th style="display:none;"></th>
                        <th>IP</th>
                        <th>აბონენტი</th>
                        <th>პოზიცია</th>
                        <th>ლოდინი დრო</th>
                      </tr>
                      ';
        
        $i = 0;
        while ($checker_row = mysql_fetch_assoc($checker)){            
            
            if($checker_row[user_id] != ''){
                $station1 .= '
                      <tr id="station">
                        <td style="display:none;">'.$checker_row[id].'</td>
                        <td>'.$checker_row[ext].'</td>
                        <td>'.$checker_row[order].'</td>
                        <td>'.$checker_row[date].'</td>
                        <td id="station_name" style="cursor: pointer;" onclick="opendialog('.$checker_row[num].',\''.$checker_row[color].'\',\''.$checker_row[name].'\',\''.$checker_row[id].'\')">'.$checker_row[name].'</td>
                        <td>'.$checker_row[ip].'</td>
                      </tr>
                      ';
                
                    $destroy_session = mysql_fetch_assoc(mysql_query("  SELECT      UNIX_TIMESTAMP(`chat_detail`.`date`) AS `date`
                                                                        FROM        `chat_detail`
                                                                        JOIN        `chat` ON `chat_detail`.`chat_id` = `chat`.`id`
                                                                        LEFT JOIN   `users` ON `chat`.`user_id` = `users`.`id`
                                                                        WHERE       `chat`.`id` = $checker_row[id]
                                                                        AND         `status`   = 0
                                                                        ORDER BY    `chat_detail`.`date` DESC
                                                                        LIMIT 1;"));
                
                    if((time() - $destroy_session[date]) > 180){
                        mysql_query("UPDATE `chat` SET `status`='1', `end_date`=NOW() WHERE (`id`='$checker_row[id]');");
                        unset($_SESSION['chat_session_id']);
                    }
            }        
            
        }
        
        while ($checker_row1 = mysql_fetch_assoc($checker1)){        
        
            if($checker_row1[user_id] == ''){
                $queu1 .= '
                      <tr id="queue">
                        <td style="display:none;">'.$checker_row1[id].'</td>
                        <td>'.$checker_row1[ip].'</td>
                        <td>'.$checker_row1[name].'</td>
                        <td>'.$checker_row1[order].'</td>
                        <td>'.$checker_row1[date].'</td>
                      </tr>
                            <script type="text/javascript">play1();</script>
                      ';
                    $destroy_session = mysql_fetch_assoc(mysql_query("  SELECT      UNIX_TIMESTAMP(`chat_detail`.`date`) AS `date`
                                                                        FROM        `chat_detail`
                                                                        JOIN        `chat` ON `chat_detail`.`chat_id` = `chat`.`id`
                                                                        LEFT JOIN   `users` ON `chat`.`user_id` = `users`.`id`
                                                                        WHERE       `chat`.`id` = $checker_row1[id]
                                                                        AND         `status`   = 0
                                                                        ORDER BY    `chat_detail`.`date` DESC
                                                                        LIMIT 1;"));
                
                    if((time() - $destroy_session[date]) > 180){
                        mysql_query("UPDATE `chat` SET `status`='1', `end_date`=NOW() WHERE (`id`='$checker_row1[id]');");
                        unset($_SESSION['chat_session_id']);
                    }
            }
        
        }
        
        $station .= $station1;
        $station .= '</table>';
        
        $queu .= $queu1;
        $queu .= '</table>';        
        
        if($station1 != ''){
            $data[chat][] = $station;
        }
        if($queu1 != ''){
            $data[chat][] = $queu;
        }        
		break;
	case 'message' :
	    $chat_id = mysql_real_escape_string($_REQUEST['id']);	    
	    
        $data = array(
	       'message' => array(),
           'whoiam' => array(),
           'stop' => array()
	    );
        $c_date		= date('Y-m-d H:i:s');
        $user       = $_SESSION['USERID'];
        
        $message = mysql_query("SELECT      IF(`chat_detail`.`type` = 1, `chat`.`name`, `users`.`username`) AS `name`,
                                            `chat_detail`.`message`,
                                            DATE_FORMAT(`chat_detail`.`date`, '%H:%i:%s') AS `date`,
                                            `chat_detail`.`type` AS `type`
                                FROM        `chat_detail`
                                JOIN        `chat` ON `chat_detail`.`chat_id` = `chat`.`id`
                                LEFT JOIN   `users` ON `chat`.`user_id` = `users`.`id`
                                WHERE       `chat`.`id` = $chat_id 
                                AND         `status`   = 0
                                ORDER BY    `chat_detail`.`date` ASC;");
        
        $chhc = mysql_num_rows($message);
        
        while ($message_row = mysql_fetch_assoc($message)){
            
            $data[message][] = '
                        <span id="chat_body_process">';
                if($message_row[type] == 2){
                        $data[message][] .= '<span style="color: #86B520;">'.mysql_real_escape_string($message_row[name]).'</span>';
                        $data[message][] .= '<span style="margin-left:6px; color: #86B520;">['.mysql_real_escape_string($message_row[date]).']:</span>';
                        $data[message][] .= '<span style="margin-left:6px; color: #86B520;">'.mysql_real_escape_string($message_row[message]).'</span>';
                }else{
                        $data[message][] .= '<span>'.mysql_real_escape_string($message_row[name]).'</span>';
                        $data[message][] .= '<span style="margin-left:6px;">['.mysql_real_escape_string($message_row[date]).']:</span>';
                        $data[message][] .= '<span style="margin-left:6px;">'.mysql_real_escape_string($message_row[message]).'</span>';
                }
                        
                        $data[message][] .= '</span>';
                        
            if($message_row[type] == 1){
                $data[whoiam][] = 1;
            }else{
                $data[whoiam][] = 0;
            }
        }
        
        $destroy_session = mysql_fetch_assoc(mysql_query("  SELECT      UNIX_TIMESTAMP(`chat_detail`.`date`) AS `date`
                                                            FROM        `chat_detail`
                                                            JOIN        `chat` ON `chat_detail`.`chat_id` = `chat`.`id`
                                                            LEFT JOIN   `users` ON `chat`.`user_id` = `users`.`id`
                                                            WHERE       `chat`.`id` = $chat_id 
                                                            AND         `status`   = 0
                                                            ORDER BY    `chat_detail`.`date` DESC
                            								LIMIT 1;"));
        
        if((time() - $destroy_session[date]) > 180){
            mysql_query("UPDATE `chat` SET `status`='1', `end_date`=NOW() WHERE (`id`='$chat_id');");
            unset($_SESSION['chat_session_id']);
        }
        
        if($chhc == 0){
            $data[message][] = '<span id="chat_body_process">
                                <span>ჩათი დახურულია</span>                        
                                </span>';
            $data[stop][] = 1;
        }
		break;
	case 'user_chat' :
	    $id_add = mysql_real_escape_string($_REQUEST['id_add']);
	    $text_add = mysql_real_escape_string($_REQUEST['text_add']);
	    $num_row = cheker($id_add);
	    $c_date		= date('Y-m-d H:i:s');
	    
	    if(!empty($id_add) and !empty($text_add) and $num_row > 0){
		  mysql_query("INSERT INTO `chat_detail` (`chat_id`, `date`, `message`, `type`) VALUES ('$id_add', NOW(), '$text_add', '2');");
        }
		break;
	case 'guest_chat':
	    $id_add = mysql_real_escape_string($_REQUEST['id_add_guest']);
	    $text_add = mysql_real_escape_string($_REQUEST['text_add_guest']);
	    $num_row = cheker($id_add);
	    $c_date		= date('Y-m-d H:i:s');
	    
	    if(!empty($id_add) and !empty($text_add)  and $num_row > 0){ 
	       mysql_query("INSERT INTO `chat_detail` (`chat_id`, `date`, `message`, `type`) VALUES ('$id_add', NOW(), '$text_add', '1');");
	    }
		break;
	case 'close_chat':
		$close_id = mysql_real_escape_string($_REQUEST['close_id']);
		$c_date		= date('Y-m-d H:i:s');
		     
	    if(!empty($close_id)){
	        mysql_query("UPDATE `chat` SET `status`='1', `end_date`=NOW() WHERE (`id`='$close_id');");
	        unset($_SESSION['chat_session_id']);
	    }
		break;	

	case 'select_chat':
		$up_id = mysql_real_escape_string($_REQUEST['up_id']);
		$user  = $_SESSION['USERID'];
		$cheker_user = cheker_user($up_id);
		     
		if(!empty($up_id) and $cheker_user > 0){
		    mysql_query("UPDATE `chat` SET `user_id`='$user' WHERE (`id`='$up_id');");
		}
		break;	
	case 'check_session':
	       if(time() - $_SESSION['GUEST_TIME'] > 20){
	           session_unset($_SESSION['GUEST_TIME']);
	       }	       
		break;
	case 'get_list' :
		    $count      = $_REQUEST['count'];
		    $hidden     = $_REQUEST['hidden'];
		    $c_date		= date('Y-m-d');
		    $rResult    = mysql_query("select  		incomming_call.id,
                                    		        incomming_call.id,
                                    		        DATE_FORMAT(incomming_call.`date`,'%y-%m-%d %H:%i:%s'),
                                    		        info_category.`name`,
                                    		        incomming_call.name,
                                    		        incomming_call.content
                    		           FROM 		incomming_call
                    		           LEFT JOIN 	info_category  ON incomming_call.information_category_id=info_category.id
                    		           LEFT JOIN	source ON incomming_call.source_id = source.id
                    		           WHERE 		incomming_call.actived = 1 AND DATE(date) = DATE(NOW()) AND source_id = 2");
		     
		    $data = array(
		        "aaData"	=> array()
		    );
		
		    while ( $aRow = mysql_fetch_array( $rResult ) )
		    {
		        $row = array();
		        for ( $i = 0 ; $i < $count ; $i++ )
		        {
		            /* General output */
		            $row[] = $aRow[$i];
		        }
		        $data['aaData'][] = $row;
		    }
		
		break;
	default:
		$error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	Request Functions
* ******************************
*/

function cheker($chat_id){
    $checker = mysql_num_rows(mysql_query(" SELECT 	`id`
                                            FROM 	`chat`
                                            WHERE 	`status`   = 0
                                            AND 	`actived`  = 1
                                            AND     `id` = '$chat_id';"));
    return $checker;
}

function cheker_user($chat_id){
    $cheker_user = mysql_num_rows(mysql_query(" SELECT 	`user_id`
                                                FROM 	`chat`
                                                WHERE 	`status`   = 0
                                                AND 	`actived`  = 1
                                                AND     `id` = '$chat_id'
                                                AND     ISNULL(`user_id`);"));
    return $cheker_user;
}

?>